/*
 * CustomerEditInfo.java
 *
 * Created on Feb 7, 2011, 4:52:10 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.datalayer.Customer;
import edu.rit.varapp.datalayer.CustomerOps;
import edu.rit.varapp.db.DatabaseConnection;
import edu.rit.varapp.logging.Logging;
import edu.rit.varapp.utilities.JTableUtils;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author Eric Kisner
 */
public class CustomerEditInfo extends javax.swing.JFrame {

    private final CustomerOps ops = new CustomerOps( DatabaseConnection.instance() );
    private int entityId;
    private JTable customerData;

    /** Creates new form CustomerEditInfo */
    public CustomerEditInfo( int entityId ) {
        initComponents();
        this.entityId = entityId;
        showData( entityId );
    }

    /**
     * Setter and getter for the dynamically created JTable that will hold the current Customer's information.
     */
    private void setCustomerData( JTable customerData ) {
        this.customerData = customerData;
    }

    private JTable getCustomerData() {
        return customerData;
    }

    /**
     * Adds the JTable to the content pane if there are no errors.
     */
    private void showData( int entityId ) {
        JTable table = null;
        try {
            table = getTable( entityId );
            setCustomerData( table );
        } catch( SQLException sqle ) {
            Logging.log( "There was an error trying to display customer information: " + sqle.getMessage(),
                         this.getClass() );
            JOptionPane.showMessageDialog( rootPane, "An error has occurred when trying to access your information."
                                                     + " Please try restarting the program." );
            System.exit( 0 );
        }

        JScrollPane holder = new JScrollPane( table );
        getContentPane().add( holder );
        holder.setBounds( 0, 10, 840, 240 );
    }

    /**
     * Creates a JTable using the Customer's information, retrieved by using their entityId.
     * @param entityId The Customer's entityId to retrieve their information.
     * @return A populated JTable with the Customer's data, or null if there was a problem retrieving/creating it.
     * @throws SQLException
     */
    private JTable getTable( int entityId ) throws SQLException {
        Customer loggedIn = ops.retrieveCustomer( entityId );

        if( loggedIn != null ) {
            String[] temp = Customer.columnsToSQL().split( "," );
            String[] header = new String[temp.length - 1];
            System.arraycopy( temp, 1, header, 0, temp.length - 1 );
            temp = loggedIn.valuesToSQL( false ).split( "," );
            String[] values = new String[temp.length - 1];
            System.arraycopy( temp, 1, values, 0, temp.length - 1 );

            //Set up a multi-dimensional array to initialize the JTable. There is only one row
            //so we only need to set the first position to the whole array of the customer field values.
            Object[][] tableRow = new Object[1][values.length];
            tableRow[0] = values;
            JTable ret = new JTable( tableRow, header );
            ret = applyOptions( ret );
            return ret;
        }
        return null;
    }

    /**
     * Apply any options to the newly-created JTable.
     */
    private JTable applyOptions( JTable table ) {
        table.setRowHeight( 30 );
        table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        table.setRowMargin( 10 );
        table.setSelectionMode( javax.swing.ListSelectionModel.SINGLE_SELECTION );
        table.setShowHorizontalLines( false );
        table.setShowVerticalLines( false );
        return table;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        applyButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(870, 300));
        setResizable(false);
        getContentPane().setLayout(null);

        applyButton.setText("Apply Changes");
        applyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyButtonActionPerformed(evt);
            }
        });
        getContentPane().add(applyButton);
        applyButton.setBounds(630, 250, 120, 23);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        getContentPane().add(cancelButton);
        cancelButton.setBounds(770, 250, 87, 23);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        new CustomerOperations( entityId ).setVisible( true );
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void applyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyButtonActionPerformed
        JTable table = getCustomerData();
        ArrayList<String> singleRow = JTableUtils.singleDataFromTable( table );
        singleRow.add( 0, entityId + "" );  //Add the entityId to the beginning of the row data.
        Customer customer = new Customer( singleRow );
        try {
            ops.updateCustomer( customer );
            JOptionPane.showMessageDialog( rootPane, "Successfully updated your information." );
        } catch( SQLException sqle ) {
            Logging.log( "Error updating customer " + customer + ": " + sqle + "\nStack trace: " + sqle.getStackTrace(),
                         this.getClass() );
            JOptionPane.showMessageDialog( rootPane, "There was a problem updating your information, "
                                                     + "please make sure you are connected to the internet "
                                                     + "and restart the application." );
            System.exit( 1 );
        }
    }//GEN-LAST:event_applyButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyButton;
    private javax.swing.JButton cancelButton;
    // End of variables declaration//GEN-END:variables
}
